package com.bugstack.domain.strategy.service.armory;

import com.bugstack.domain.strategy.model.entity.StrategyAwardEntity;
import com.bugstack.domain.strategy.model.entity.StrategyEntity;
import com.bugstack.domain.strategy.model.entity.StrategyRuleEntity;
import com.bugstack.domain.strategy.repository.IStrategyRepository;
import com.bugstack.types.common.Constants;
import com.bugstack.types.enums.ResponseCode;
import com.bugstack.types.exception.AppException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.util.*;

/**
 * @Author: czb
 * @Description: 策略装配库，负责初始化策略计算
 * @DateTime: 2025/3/3 16:46
 **/
@Service
public class StrategyArmoryDispatch implements IStrategyArmory,IStrategyDispatch{

    @Resource
    private IStrategyRepository strategyRepository;


    @Override
    public Boolean assembleLotteryStrategy(Long strategyId) {
        //1.先查策略配置
        List<StrategyAwardEntity> strategyAwardEntities =
                strategyRepository.queryStrategyAwardList(strategyId);


        //2.缓存奖品数量
        for (StrategyAwardEntity strategyAwardEntity : strategyAwardEntities) {
            Integer awardCount = strategyAwardEntity.getAwardCount();
            Integer awardId = strategyAwardEntity.getAwardId();
            cacheStrategyAwardCount(strategyId, awardCount, awardId);
        }

        assembleLotteryStrategy(String.valueOf(strategyId), strategyAwardEntities);

        //3.权重策略配置 -适用于rule_weight权重规则配置
        StrategyEntity strategyEntity = strategyRepository.queryStrategyById(strategyId);
        String ruleWeight = strategyEntity.getRuleWeights();
        if(null == ruleWeight) return true;

        //3.查询规则权重配置
        StrategyRuleEntity strategyRuleEntity = strategyRepository.queryStrategyRule(strategyId, ruleWeight);
        if (null == strategyRuleEntity) {
            throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode(), ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());
        }
        Map<String, List<Integer>> ruleWeights = strategyRuleEntity.getRuleWeights();

        //4.过滤奖励id，放入缓存
        for (String key : ruleWeights.keySet()) {
            ArrayList<StrategyAwardEntity> strategyAwardEntitiesClone = new ArrayList<>(strategyAwardEntities);
            List<Integer> containedAwardIds = ruleWeights.get(key);
            strategyAwardEntitiesClone.removeIf(entity -> !containedAwardIds.contains(entity.getAwardId()));
            assembleLotteryStrategy(String.valueOf(strategyId).concat("_").concat(key), strategyAwardEntitiesClone);
        }
        return true;
    }

    @Override
    public Boolean assembleLotteryStrategyByActivityId(Long activityId) {
        Long strategyId = strategyRepository.queryStrategyIdByActivityId(activityId);
        return assembleLotteryStrategy(strategyId);
    }

    private void assembleLotteryStrategy(String key, List<StrategyAwardEntity> strategyAwardEntities){
        //1.获取概率总值
        BigDecimal totalRate = strategyAwardEntities.
                stream().
                map(StrategyAwardEntity::getAwardRate).
                reduce(BigDecimal::add).orElse(BigDecimal.ZERO);

        //2.获取概率最小值
        BigDecimal minRate = strategyAwardEntities.stream().
                map(StrategyAwardEntity::getAwardRate)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);

        //3.获取概率范围，百分位、千分位、万分位
        BigDecimal rateRange = totalRate.divide(minRate, 0, RoundingMode.CEILING);

        //4.填充奖励表
        ArrayList<Integer> strategyAwardSearchTables = new ArrayList<>(rateRange.intValue());
        for (StrategyAwardEntity strategyAwardEntity : strategyAwardEntities) {

            BigDecimal awardRate = strategyAwardEntity.getAwardRate();
            int count = rateRange.multiply(awardRate).setScale(0, RoundingMode.CEILING).intValue();
            for (int i = 0; i<count;i++){
                strategyAwardSearchTables.add(strategyAwardEntity.getAwardId());
            }
        }

        //5.打乱顺序
        Collections.shuffle(strategyAwardSearchTables);

        //6.生成map
        HashMap<Integer, Integer> shuffleStrategyAwardSearchTables = new HashMap<>();
        for (int i = 0; i < strategyAwardSearchTables.size(); i++) {
            shuffleStrategyAwardSearchTables.put(i, strategyAwardSearchTables.get(i));
        }

        //7.存入redis
        strategyRepository.
                storeStrategyAwardSearchTables(key,
                        shuffleStrategyAwardSearchTables.size(),
                        shuffleStrategyAwardSearchTables);
    }


    @Override
    public Integer getRandomAwardId(Long strategyId) {
        // 分布式部署下，不一定为当前应用做的策略装配。也就是值不一定会保存到本应用，而是分布式应用，所以需要从 Redis 中获取。
        int rateRange = strategyRepository.getRateRange(strategyId);

        // 通过生成的随机值，获取概率值奖品查找表的结果
        return strategyRepository.getStrategyAwardAssemble(String.valueOf(strategyId), new SecureRandom().nextInt(rateRange));
    }

    @Override
    public Integer getRandomAwardId(Long strategyId, String ruleWeightValue) {
        String key = String.valueOf(strategyId).concat("_").concat(ruleWeightValue);

        // 分布式部署下，不一定为当前应用做的策略装配。也就是值不一定会保存到本应用，而是分布式应用，所以需要从 Redis 中获取。
        int rateRange = strategyRepository.getRateRange(key);

        // 通过生成的随机值，获取概率值奖品查找表的结果
        return strategyRepository.getStrategyAwardAssemble(key, new SecureRandom().nextInt(rateRange));
    }

    private void cacheStrategyAwardCount(Long strategyId, Integer awardCount, Integer awardId) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE +awardId;
        strategyRepository.cacheStrategyAwardCount(cacheKey, awardCount);
    }


    @Override
    public boolean subtractionAwardStock(Long strategyId, Integer awardId, Date endDateTime) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE +awardId;
        return strategyRepository.subtractionAwardStock(cacheKey, endDateTime);
    }
}
